<template>
	<view class="container">
		<view class="camera-container">
			<view class="camera-guide">
				<text>请将摄像头对准人脸</text>
			</view>
			<view class="camera-view">
				<camera style="width:300px;height:300px;border-radius:10000px;margin: 0 auto;" device-position="front"
					@stop="onCameraStop" @error="onCameraError" @initdone="onCameraInitDone"
					@scanresult="onScanResult" />
			</view>
			<view class="result-container">
				<button :type="isDisabled ? 'disabled':'primary'" :disabled="isDisabled" @click="onButtonClick">签到</button>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/utils/request.js';
	export default {
		data() {
			return {
				imageBase64: '',
				lessonId: null,
				isDisabled:false,
			};
		},
		onLoad(option) {
			this.lessonId = option.lessonId;
		},
		methods: {
			getDetail(){
				request.post(`/lesson/detail?lessonId=${this.lessonId}`)
				.then(res=>{
					let lesson = res.data;
					this.isDisabled = lesson.hasSigned;
				});
			},
			onCameraStop(event) {
				console.log('Camera stopped', event);
			},
			onCameraError(event) {
				console.error('Camera error', event);
			},
			onCameraInitDone(event) {
				console.log('Camera init done', event);
			},
			onScanResult(event) {
				console.log('Scan result', event);
			},
			onButtonClick() {
				const camera = uni.createCameraContext();
				camera.takePhoto({
					quality: 'high',
					success: (res) => {
						console.log('照相结果:',res);
						uni.getFileSystemManager().readFile({
							filePath: res.tempImagePath,
							encoding: 'base64',
							success: r => {
								this.imageBase64 = `data:image/png;base64,${r.data}`;
								// console.log('照片base64:',this.imageBase64);
								request.post('/sign/signWithFace',{photoBase64:this.imageBase64,lessonId:this.lessonId})
								.then(res=>{
									if(res.success){
										uni.showToast({
											title:'打卡成功'
										})
									}
								});
							}
						});
					},
					fail: (err) => {
						console.log(err);
					}
				});
			}
		}
	};
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100vh;
	}

	.camera-container {
		width: 100%;
		height: 100%;
	}

	.camera-view {
		margin-top: 50px;
	}

	.camera-guide {
		width: 100%;
		text-align: center;
		margin-top: 20px;
	}

	.result-container {
		margin-top: 30px;
		font-size: 24px;
		color: #333;
		text-align: center;
	}
</style>